package com.ruoyi.dm.component;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.CollectFileTypeConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.biz.BizModule;
import com.ruoyi.common.utils.biz.PathUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.dm.domain.po.CollectTleRecordPO;
import com.ruoyi.dm.domain.po.SpaceTrackCollectRecordPO;
import com.ruoyi.dm.service.ICollectTleRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * 空间目标数据 TLE
 */
@Component
@Slf4j
public class TleDataStrategy implements DataStrategy<SpaceTrackCollectRecordPO> {

    @Autowired
    private ICollectTleRecordService recordService;

    @Override
    public SpaceTrackCollectRecordPO makeupPo(SpaceTrackCollectRecordPO po) {
        //读取文件 首末 读取时间
        String fileName = po.getFileName();
        DateTime dateTime = null;
        if (fileName.toLowerCase().startsWith("alldata")) {
            String[] split = fileName.split("_|\\.");
            //alldata_2024_165.txt
            DateTime yyyyMMdd = DateUtil.parse(split[1] + "0101", "yyyyMMdd");
            dateTime = DateUtil.offsetDay(yyyyMMdd, Integer.valueOf(split[2])-1);
        }else if (fileName.endsWith("TLE.txt")) {
            //20220101TLE.txt
            String substring = fileName.substring(0, 8);
            dateTime = DateUtil.parse(substring, "yyyy-MM-dd");
        }
        po.setFileDate(dateTime);
        return po;
    }

    @Override
    public String pythonCmd(String satellite, String dataType, String filePath, String method, Integer year) {

        String fileType = CollectFileTypeConstants.TYPE_TLE;
        // 将配置写入 inputTLEDataProcess.txt
        //    inputTLEFilePath="/mnt/hgfs/testTleDataAlgo/data/testTLEData/Input/grace150101.txt"
        //    outputPath="/mnt/hgfs/testTleDataAlgo/data/testTLEData/test_out/"
        String outPath = PathUtil.outputModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType  ;
        String tmpPath = PathUtil.tmpModuleDir(BizModule.COLLECT) + PathUtil.moduleDirs().getCollect().get("result") + "/" + fileType + "/" ;
        String inoutJson = tmpPath + UUID.fastUUID() + ".json";
        HashMap<String, String> param = new HashMap<>();
        param.put("inputTLEFilePath",filePath);
        param.put("outputPath",outPath);

        log.info("inputTLEDataProcess={}", param);
        File file = FileUtil.writeString(JSONUtil.toJsonStr(param), inoutJson, "utf-8");
        String script = PathUtil.moduleDirs().getCollect().get("tleScript");
        String[] cmdLines = new String[2];
        cmdLines[0] = script;
        cmdLines[1] = file.getAbsolutePath();//配置文件
        String commond = ArrayUtil.join(cmdLines, " ");
        log.info("拼接脚本:{}", commond);
        return commond;
    }


    @Override
    public void save(String satellite, String outFile) throws Exception {
        //文件除重
        //根据卫星
        //1 27391U 02012A   15001.94848096  .00014359  00000-0  21490-3 0  9993
        //2 27391 089.0043 089.5541 0012146 087.5798 009.3740 15.54771002716939
        BufferedReader acc = new BufferedReader(new FileReader(outFile));
        ArrayList<CollectTleRecordPO> list = new ArrayList<>(1000);
        String line1 = "";
        String line2 = "";
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
        while (null != (line1 = acc.readLine()) && null != (line2 = acc.readLine())) {
            //2行共存
            String statellite = line1.substring(2, 7).trim();
            //年记日
            BigDecimal decimal = new BigDecimal(line1.substring(18, 32));
            Date date  = parseTleToDate(line1, pattern);
            CollectTleRecordPO po = CollectTleRecordPO.builder().tleCode(statellite).tleTime(decimal).line1(line1).line2(line2).dataTime(date).build();
            list.add(po);
            if (list.size() >= 1000) {
                recordService.saveBatch(list);
                list = new ArrayList<>(1000);
            }
        }
        recordService.saveBatch(list);
        ////除重
        //recordService.repeatRemove();
    }

    public static Date parseTleToDate(String line1,DateTimeFormatter pattern ) throws ParseException {
        int year = Integer.valueOf(line1.substring(18, 20));
        if (year>57) {
            year+=1900;
        }else {
            year+=2000;
        }
        int day = Integer.valueOf(line1.substring(20, 23));
        Long sec = Double.valueOf(Double.valueOf("0."+line1.substring(24, 32))*86400).longValue();
        LocalTime localTime = LocalTime.ofSecondOfDay(sec);
        LocalDate localDate = LocalDate.ofYearDay(year, day);
        LocalDateTime of = LocalDateTime.of(localDate, localTime);
        String format = of.format(pattern);
        Date date = DateUtils.parseDate(format, "yyyy-MM-dd-HH-mm-ss");
        return date;
    }
}
